package handle

import (
	"bookProjectSrv/model"
	user "bookProjectSrv/proto"
	"context"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type UserServer struct {
	user.UnimplementedUserServer
}

func (u *UserServer) GetUser(ctx context.Context, req *user.GetUserReq) (*user.GetUserRes, error) {
	userMod := model.NewUser()
	id := req.Id
	infos, err := userMod.Get(int(id))
	if err != nil {
		zap.S().Info("注册提交入库失败原因:::::::", err.Error)
		panic(err)
	}
	pb, err := mysqlToPb(infos)
	if err != nil {
		return nil, err
	}
	return &user.GetUserRes{Info: pb}, nil
}

func (u UserServer) CreateUser(ctx context.Context, request *user.CreateReq) (*user.CreateRes, error) {
	userMod := model.NewUser()
	info := request.Info
	infos, err := userMod.Regester(pbToMysql(info))
	if err != nil {
		zap.S().Info("注册提交入库失败原因:::::::", err.Error)
		panic(err)
	}
	pb, err := mysqlToPb(infos)
	if err != nil {
		return nil, err
	}
	return &user.CreateRes{Info: pb}, nil
}

func (u UserServer) GetUserByUsername(ctx context.Context, request *user.GetUserByUsernameReq) (*user.GetUserByUsernameRes, error) {
	userMod := model.NewUser()
	infos, err := userMod.GetByUsername(request.Username)
	if err != nil {
		return nil, err
	}
	pb, err := mysqlToPb(infos)
	if err != nil {
		return nil, err
	}
	return &user.GetUserByUsernameRes{Info: pb}, nil
}

func pbToMysql(in *user.UserInfo) *model.User {
	return &model.User{
		Model: gorm.Model{
			ID: uint(in.Id),
		},
		Username: in.Username,
		Password: in.Password,
		Email:    in.Email,
		Mobile:   in.Mobile,
		Salt:     in.Salt,
		Sex:      int(in.Sex.Number()),
	}
}

// 从数据库中获取的用户信息
func mysqlToPb(info *model.User) (*user.UserInfo, error) {
	return &user.UserInfo{
		Id:       int64(info.ID),
		Username: info.Username,
		Password: info.Password,
		Email:    info.Email,
		Mobile:   info.Mobile,
		Salt:     info.Salt,
		Sex:      user.Sex(info.Sex),
	}, nil
}
